package com.gopay.bis.citic.fund.operation;


import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.InputStream;
import java.util.*;

/**
 * 与中信监管通信处理类
 * @StringMessage.java
 * @author dong-wang5@hnari.com
 * @2016年7月20日 上午10:03:12  www.gopay.com.cn Inc.All rights reserved.
 */
public class StringMessage {
    private static Logger logger = Logger.getLogger(StringMessage.class);

    /**
     * 根据键值对从报文中取出签名串：sign
     * @param map
     * @param name
     * @return
     */
    public String getSign(Map<String,String> map ,String name){
        if (map.size()==0) return null;
        String sign="";
        try{
            sign = map.get(name);
            if (sign == null || "".equals(sign)) return null;
        }catch(Exception e){
            logger.error(e);
        }
        return sign;
    }

    /**
     * 签名时获取非签名串
     * @param map
     * @return
     */
    public String getRealMessage(Map<String,String> map){
        String realMsg="";
        try{
            if(map.size()==0) return null;
            map.remove("sign");
            map.remove("sign_type");
            CipherStringBuilder csb = new CipherStringBuilder();
            realMsg = csb.sortingMapToStr(map,null,null,true);
            return realMsg;
        }catch (Exception e){
            logger.info(e);
            return null;
        }
    }

    public String getValue(String src,String name){
        if (src == null) return null;
        if(StringUtils.isEmpty(name)) return "";
        String xmlMsg;
        InputStream is = null;
        try{
            xmlMsg = Utils.PairStr2XML(src,"=","&");
            is = Utils.bytesToInputStream(xmlMsg.getBytes("utf-8"));
        }catch (Exception e){
            logger.error(e);
        }
        return Utils.getElementValueFromXmlIns(is,name);
    }

    public List<String> getNodeList(InputStream is){
        List<String> nodeList = new ArrayList<String>();
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db;
        try{
            db = dbf.newDocumentBuilder();
            Document doc = db.parse(is);
            NodeList nls = doc.getElementsByTagName("ROOT");
            for (int i = 0; i < nls.getLength(); i++) {
                Node node = nls.item(0);
                NodeList nodes = node.getChildNodes();
                for (int j = 0; j < nodes.getLength(); j++) {
                    Node n2 = nodes.item(j);
                    if (n2.getNodeType() == 1){
                        nodeList.add(n2.getNodeName());
                    }
                }
            }
        }catch(Exception e){
            logger.error(e.getMessage());
        }
        return nodeList;
    }

    /**
     * 将list转化成string数组
     * @param list
     * @return
     */
    public String[] getStringArrayByList(List<String> list){
        String[] tagNames = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            tagNames[i] = list.get(i);
        }
        return tagNames;
    }

    /**
     * @param flg
     * @param xmlIs 代表CML的流
     * @param tagnames 关注的字段
     * @param connector 连接键值的符号
     * @param seperator 连接键值对的符号
     * @param isAscending 是否升序排列
     * @return
     */
    public String XML2PairStr(String flg,InputStream xmlIs,String[] tagnames,String connector,
                              String seperator,boolean isAscending){
        Map<String,String> disorderMap = getElementValuesFromXmlIns(flg,xmlIs,tagnames);
        return CipherStringBuilder.sortingMapToStr(disorderMap,connector,seperator,isAscending);
    }

    public static Map<String,String> getElementValuesFromXmlIns(String flg,InputStream is,String[] tagNames){
        String nodeValue = null;
        Map<String,String> disorderMap = new HashMap<String,String>();
        try{
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document dc = db.parse(is);
            Element root = dc.getDocumentElement();
            for (String tagName : tagNames) {
                NodeList nodes = root.getElementsByTagName(tagName);
                if (nodes!=null && nodes.getLength()>1){
                    throw new ParserConfigurationException("元素重复，检查报文");
                }
                if (nodes ==null || nodes.item(0)==null || nodes.item(0).getFirstChild()==null){
                    disorderMap.put(tagName,null);
                }else{
                    Node node = nodes.item(0);//只处理第一个元素
                    nodeValue = node.getFirstChild().getNodeValue();
                    if (flg.equals("C") && "service".equals(tagName)){
//                        disorderMap.put(tagName,TranCodeUtil.getCode(nodeValue));
                    }else if(flg.equals("S") && "service".equals(tagName)){
//                        nodeValue = TranCodeUtil.getService(nodeValue);
                        disorderMap.put(tagName,nodeValue);
                    }else{
                        disorderMap.put(tagName,nodeValue);
                    }
                }
            }
        }catch(Exception e){
            logger.error(e);
        }
        return disorderMap;
    }

    public Map<String,String> getReceivedMap(HttpServletRequest request){
        Map<String ,String[]> requestMap = request.getParameterMap();
        Set<String> keySet = requestMap.keySet();
        Map<String,String> map = new HashMap<String,String>();
        for (String key : keySet) {
            String value = (requestMap.get(key))[0];
            map.put((String)key ,value);
        }
        return map;
    }
}
